using System.Net;
using System.Threading;
using Xunit;
using Xunit.Abstractions;

namespace SmartSite.Network.Test
{
    public class TestSocket
    {
        private readonly ITestOutputHelper Output;

        public TestSocket(ITestOutputHelper output)
        {
            Output = output;
        }

        [Theory]
        [InlineData("127.0.0.1", 2204, 1024)]
        public void TestSendToSelfAndRecevieFrame(string ipaddress, int port, int length)
        {
            //Given
            using (AsyncSocket socket = new AsyncSocket(port, length))
            {
                socket.StartReceiving();

                byte[] buffer = new byte[length];
                for (int i = 0; i < length; i++)
                    buffer[i] = (byte)i;

                //When

                //Then
                Assert.RaisedEvent<SocketStateEventArgs> evt = Assert.Raises<SocketStateEventArgs>(
                    (h) => socket.OnReceived += h,
                    (h) => socket.OnReceived -= h,
                    () =>
                    {
                        socket.SendTo(IPAddress.Parse(ipaddress), buffer);
                        Thread.Sleep(1000);
                    });
                Assert.NotNull(evt);
                Assert.Equal(socket, evt.Sender);
                Assert.Equal(length, (int)evt.Arguments.BufferLength);
                for (int i = 0; i < length; i++)
                {
                    Assert.Equal($"{i}: {buffer[i]:X2}", $"{i}: {evt.Arguments.BufferClone()[i]:X2}");
                }
            }
        }
    }
}